<template>
  <div>
    <van-nav-bar left-arrow @click-left="leftClick"></van-nav-bar>
    <h4 class="title">短信登录</h4>
    <div class="form">
      <van-form ref="form">
        <!-- :rules="rules" -->
        <van-field
          v-model="form.mobile"
          :rules="rules.mobile"
          placeholder="请输入手机号"
          name="mobile"
        ></van-field>
        <van-field
          v-model="form.code"
          :rules="rules.code"
          placeholder="请输入验证码"
        >
          <template #button>
            <div @click="getCode" class="Code" v-if="totalTIme === 6">
              发送验证码
            </div>
            <div class="Code" v-else>{{ totalTIme }}秒后再试</div>
          </template>
        </van-field>
        <van-button type="primary" class="btn" @click="submit">登录</van-button>
      </van-form>
    </div>
  </div>
</template>

<script>
// 导入的方法要写在一起，不能每个方法都分开导入，会报eslint错误
import { authorizations, smsCodes } from '@/api/user.js'
export default {
  data () {
    return {
      totalTIme: 6,
      interval: '',
      form: {
        mobile: '13200000000',
        code: '246810'
      },
      rules: {
        mobile: [
          { required: true, message: '必填', trigger: 'onChange' },
          {
            validator: value => {
              const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              return reg.test(value)
            },
            message: '请输入11位手机号',
            trigger: 'onChange'
          }
        ],
        code: [
          { required: true, message: '必填', trigger: 'onChange' },
          {
            validator: value => {
              return value.length === 6
            },
            message: '请输入6位验证码',
            trigger: 'onChange'
          }
        ]
      }
    }
  },
  beforeDestroy () {
    // 需求：用户可能在获取验证码的途中点击跳转了【leftClick ()】其他页面，避免浪费性能，要在渲染页面前清除掉计时器
    clearInterval(this.interval)
  },
  methods: {
    leftClick () {
      console.log('左箭头')
      //   this.$router.go(0) 当前页面
      //   this.$router.go(-1) 上一页面 如果用户上一个页面是在其他网页，用.go()的方法会去掉其他的网页
      // 避免上面的问题出现，直接写死
      this.$router.push('/')
    },
    getCode () {
      //   console.log('获取验证码')
      //  验证手机号是否输入正确 给van-form 绑定ref属性
      this.$refs.form
        .validate('mobile') // 验证项：绑定name值
        .then(async () => {
          // 设置短信验证码倒计时
          this.totalTIme--
          this.interval = setInterval(() => {
            this.totalTIme--
            // 倒计时等于0时清掉计时器
            if (this.totalTIme <= 0) {
              clearInterval(this.interval)
              // 还原时间
              this.totalTIme = 6
            }
          }, 1000)
          await smsCodes(this.form.mobile)
          this.$toast.success('验证码发送成功')
          //   console.log(res)
        })
      // .catch(() => {
      //   this.$toast.fail('验证失败')
      // })
    },
    submit () {
      // 全局验证 给van-form 绑定ref属性
      this.$refs.form.validate().then(async () => {
        //   this.$toast.success('验证成功')
        this.$toast.loading({ duration: 2000 })
        const res = await authorizations(this.form)
        console.log('用户登录', res)
        //  存在token
        this.$store.commit('user/getState', res.data.token)
        this.$toast.success('登录成功')
        // 跳转到相应路由
        const path = this.$route.query.redirect || '/'
        this.$router.push(path)
      })
      // .catch(() => {
      //   this.$toast.fail('验证失败')
      // })
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .van-nav-bar .van-icon {
  color: #999;
}
.form {
  padding: 15px;
}
.title {
  font-weight: 400;
  padding: 20px;
}

.btn {
  margin-top: 15px;
  width: 100%;
}
.Code {
  color: #ccc;
}
</style>
